package com.bg.print.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.bg.print.config.pay.AliPay;
import com.bg.print.config.pay.AliPayConfig;
import com.bg.print.entity.OrderEntity;
import com.bg.print.entity.UserEntity;
import com.bg.print.service.OrderService;
import com.bg.print.service.UserService;
import com.bg.print.utils.R;
import com.bg.print.variable.OrderCancel;
import com.bg.print.variable.OrderStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Tag(name = "支付")
@RestController
@Slf4j
@RequestMapping("/alipay")
public class AliPayController {
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";
    @Resource
    private AliPayConfig aliPayConfig;
    @Resource
    private OrderService orderService;
    @Resource
    private UserService userService;
    @Operation(summary = "支付(直接调用)   /alipay/pay?subject=test1&outTradeNo=1776270799023525898&totalAmount=29&userId=23")
    @GetMapping("/pay")
    @PreAuthorize("hasAuthority('BUYER')")
    //    http://110.42.14.112:48506/alipay/pay?subject=test1&outTradeNo=1776270799023525000&totalAmount=29
    public R pay(AliPay aliPay, HttpServletResponse httpResponse, @AuthenticationPrincipal UserDetails userDetails) throws Exception {
        OrderEntity byId = orderService.getByIdAndUser(aliPay.getOutTradeNo(), userDetails, aliPay.getTotalAmount());
        if (byId == null) {
            throw new RuntimeException("订单支付错误");
        }
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        //同步跳转地址
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", aliPay.getOutTradeNo());  // 我们自己生成的订单编号
        bizContent.set("total_amount", aliPay.getTotalAmount()); // 订单的总金额
        bizContent.set("subject", aliPay.getSubject());   // 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            log.error(e.toString());
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        return null;
    }

    @Operation(summary = "回调(不可调用)")
    //这个接口是支付完成以后支付宝沙箱回调接口
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            log.info("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
                // 验签通过
                log.info("交易名称: " + params.get("subject"));
                log.info("交易状态: " + params.get("trade_status"));
                log.info("支付宝交易凭证号: " + params.get("trade_no"));
                log.info("商户订单号: " + params.get("out_trade_no"));
                log.info("交易金额: " + params.get("total_amount"));
                log.info("买家在支付宝唯一id: " + params.get("buyer_id"));
                log.info("买家付款时间: " + params.get("gmt_payment"));
                log.info("买家付款金额: " + params.get("buyer_pay_amount"));

                OrderEntity orderEntity = new OrderEntity();
                orderEntity.setStatus(OrderStatus.COMPLETE_PAYMENT.getCode());
                orderEntity.setTradeNo(params.get("trade_no"));
                orderEntity.setTotalAmount(new BigDecimal(params.get("total_amount")));
                orderEntity.setBuyerId(params.get("buyer_id"));
                orderEntity.setGmtPayment(new Date());
                orderEntity.setPayment(new BigDecimal(params.get("buyer_pay_amount")));
                // 更新订单已支付
                Integer ok = orderService.buy(orderEntity, Long.parseLong(params.get("out_trade_no")), new BigDecimal(params.get("buyer_pay_amount")));
            }
        }
        return "success";
    }
    @Operation(summary = "(同意取消订单加退款操作)同意取消")
    @GetMapping("/return")
    @PreAuthorize("hasAuthority('ADMIN') or hasAuthority('MERCHANT')")
    // http://127.0.0.1:8080/alipay/return?traceNo=2024040922001404770502237072&outTradeNo=1776270799023525000&totalAmount=29&userId=23
    public R returnPay(AliPay aliPay) throws AlipayApiException {
        OrderEntity orderEntity = orderService.getById(aliPay.getOutTradeNo());
        if (orderEntity == null) {
            log.error("同意取消订单失败");
            return R.error(500, "同意取消订单失败");
        }
        if (!Objects.equals(orderEntity.getCancel(), OrderCancel.REQUEST_ORDER_CANCELLATION.getCode())) {
            log.error("同意取消订单失败");
            return R.error(500, "同意取消订单失败");
        }
        if (orderEntity.getStatus()< OrderStatus.COMPLETE_PAYMENT.getCode()) {
            orderEntity.setCancel(OrderCancel.AGREE_TO_CANCEL_THE_ORDER.getCode());
            orderService.updateById(orderEntity);
            log.info("成功");
            return R.ok();
        }
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,
                aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET,
                aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        // 2. 创建 Request，设置参数
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.set("trade_no", aliPay.getTraceNo());  // 支付宝回调的订单流水号
        bizContent.set("refund_amount", aliPay.getTotalAmount());  // 订单的总金额
        bizContent.set("out_request_no", aliPay.getTraceNo());   //  我的订单编号

        request.setBizContent(bizContent.toString());

        // 3. 执行请求
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {  // 退款成功，isSuccess 为true
            log.info("退款成功");
            orderEntity.setCancel(OrderCancel.AGREE_TO_CANCEL_THE_ORDER.getCode());
            orderEntity.setDTime(new Date());
            orderService.updateById(orderEntity);
            return R.ok();
        } else {
            log.info("退款失败");
            return R.error(500, "退款失败");
        }
    }
}
